﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;
using MM.DBUtility;
using MM.Common;

namespace MobileManager
{
    public partial class RTByCN : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        private int intLWNum = 0, intAllNum = 0;
        private bool Flag = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }
            else
            {
                userModel = (MM.Model.T_Users)Session["CurUser"];
            }
            if (!IsPostBack)
            {
                BindDdlCustomer(ref ddlCustomer);
                ddlCustomer.Items.Insert(0, new ListItem("全部", "-1"));

                BindDdlODEP(ref ddlODEP);
                ddlODEP.Items.Insert(0, new ListItem("全部", "-1"));

                inputDateFrom.Value = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                inputDateTo.Value = DateTime.Now.ToString("yyyy-MM-dd");

                GVDataBind();
            }
        }
        private void BindDdlCustomer(ref DropDownList ddl)
        {
            string strSQL = "SELECT CNO,CNO+'-'+ CName as Name FROM T_Customers WITH(NOLOCK)";
            if (!string.IsNullOrEmpty(userModel.CustomerNO))
                strSQL += string.Format("WHERE CNO IN ({0})", BLSqlData.GetInSQL(userModel.CustomerNO));
            ddl.DataSource = DbHelperSql.Query(strSQL).Tables[0];
            ddl.DataValueField = "CNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindDdlODEP(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ONO,ONO+'-'+ OName as Name FROM T_ODEP WITH(NOLOCK)").Tables[0];
            ddl.DataValueField = "ONO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                {
                    if (Convert.ToDateTime(inputDateFrom.Value) > Convert.ToDateTime(inputDateTo.Value))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "请求时间From必须小于等于To！");
                        return;
                    }
                }
                else
                {
                    MM.Common.Common.PageStartAlert(this.Page, "时间From,To必须填写！");
                    return;
                }
                Flag = false;
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnQueryAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                {
                    if (Convert.ToDateTime(inputDateFrom.Value) > Convert.ToDateTime(inputDateTo.Value))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "请求时间From必须小于等于To！");
                        return;
                    }
                }
                else
                {
                    MM.Common.Common.PageStartAlert(this.Page, "时间From,To必须填写！");
                    return;
                }
                Flag = true;
                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region GV Bind
        private void GVDataBind()
        {
            string strSQLF = string.Format("SELECT DISTINCT a.CNO,a.IMSI FROM T_SIMall1 a WITH(NOLOCK) WHERE a.CreateTime<'{0}' ", Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));
            if (!"-1".Equals(ddlCustomer.SelectedValue))
                strSQLF += string.Format(" AND a.CNO='{0}'", ddlCustomer.SelectedValue);
            if (!"-1".Equals(ddlODEP.SelectedValue))
                strSQLF += string.Format(" AND a.ONO='{0}'", ddlODEP.SelectedValue);

            string strSQL = string.Format("SELECT CNO,COUNT(CNO) AS AllNum FROM ({0}) AS A GROUP BY CNO", strSQLF);

            intLWNum = 0; intAllNum = 0;
            List<LWCGL> Rdate = GetData(strSQL);
            GetData(ref Rdate);
            GVinfo.DataSource = Rdate;
            GVinfo.DataBind();
            ViewState["DataTemp"] = Rdate;
            lbCount.Text = "记录数：" + Rdate.Count;

            lbLWNum.Text = "总联网数：" + intLWNum.ToString();
            lbAllNum.Text = "总IMSI数：" + intAllNum.ToString();
            lbRnumAll.Text = "总联网率：" + (intLWNum / intAllNum.ToDouble()).ToString("P");
        }

        private void GVDataBindAll()
        {
            string strSQLF = string.Format("SELECT DISTINCT a.CNO,a.IMSI FROM T_SIMall1 a WITH(NOLOCK) WHERE a.CreateTime<'{0}' ", Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

            string strSQL = string.Format("SELECT CNO,COUNT(CNO) AS AllNum FROM ({0}) AS A GROUP BY CNO", strSQLF);

            intLWNum = 0; intAllNum = 0;
            List<LWCGL> Rdate = GetData(strSQL);
            GetData(ref Rdate);
            GVinfo.DataSource = Rdate;
            GVinfo.DataBind();
            ViewState["DataTemp"] = Rdate;
            lbCount.Text = "记录数：" + Rdate.Count;

            lbLWNum.Text = "总联网数：" + intLWNum.ToString();
            lbAllNum.Text = "总IMSI数：" + intAllNum.ToString();
            lbRnumAll.Text = "总联网率：" + (intLWNum / intAllNum.ToDouble()).ToString("P");
        }

        protected void GVinfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GVinfo.PageIndex = e.NewPageIndex;
            GVinfo.DataSource = (List<LWCGL>)ViewState["DataTemp"];
            GVinfo.DataBind();
        }
        #endregion

        private List<LWCGL> GetData(string strSQL)
        {
            List<LWCGL> Rdate = new List<LWCGL>();
            DataSet ds = DbHelperSql.Query(strSQL);
            if (ds != null && ds.Tables.Count > 0)
            {
                LWCGL obj = null;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    obj = new LWCGL();
                    obj.CNO = row["CNO"].ToString();
                    obj.AllNum = row["AllNum"].ToInt();
                    obj.LWRum = GetLWRum(obj.CNO);
                    obj.Rate = obj.AllNum.Equals("0") ? 0 : (obj.LWRum.ToInt() / obj.AllNum.ToDouble());
                    Rdate.Add(obj);

                    intLWNum += obj.LWRum;
                    intAllNum += obj.AllNum;
                }
            }
            return Rdate;
        }
        private int GetLWRum(string strCNO)
        {
            int intResult = 0;
            string strSQLF = string.Format("SELECT DISTINCT a.IMSI FROM T_SIMall1 a WITH(NOLOCK) WHERE a.CNO='{0}' AND a.CreateTime BETWEEN '{1}' AND '{2}' ", strCNO, inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

            if (!Flag && !"-1".Equals(ddlODEP.SelectedValue))
                strSQLF += string.Format(" AND a.ONO='{0}'", ddlODEP.SelectedValue);

            object oCount = DbHelperSql.GetSingle(string.Format("SELECT COUNT(1) FROM ({0}) AS B", strSQLF));
            if (oCount != null)
                intResult = oCount.ToInt();
            return intResult;
        }
        private void GetData(ref List<LWCGL> SortData)
        {
            if (SortData != null && SortData.Count > 0)
            {
                if (ddlOrder.SelectedValue.Equals("1"))//成功率
                {
                    if ("ASC".Equals(ddlAD.SelectedValue))
                        SortData = SortData.OrderBy(e => e.Rate).ToList();
                    else
                        SortData = SortData.OrderByDescending(e => e.Rate).ToList();
                }
                else if (ddlOrder.SelectedValue.Equals("2"))//IMSI总数
                {
                    if ("ASC".Equals(ddlAD.SelectedValue))
                        SortData = SortData.OrderBy(e => e.AllNum).ToList();
                    else
                        SortData = SortData.OrderByDescending(e => e.AllNum).ToList();
                }
                else if (ddlOrder.SelectedValue.Equals("3"))//IMSI联网数
                {
                    if ("ASC".Equals(ddlAD.SelectedValue))
                        SortData = SortData.OrderBy(e => e.LWRum).ToList();
                    else
                        SortData = SortData.OrderByDescending(e => e.LWRum).ToList();
                }
            }
        }
        public string CVrate(string strValue)
        {
            return strValue.ToDouble().ToString("P");
        }
    }
    [Serializable]
    public class LWCGL
    {
        private string _CNO;
        private int _LWRum;
        private int _AllRum;
        private double _Rate;

        public string CNO
        {
            set { _CNO = value; }
            get { return _CNO; }
        }

        public int LWRum
        {
            set { _LWRum = value; }
            get { return _LWRum; }
        }

        public int AllNum
        {
            set { _AllRum = value; }
            get { return _AllRum; }
        }

        public double Rate
        {
            set { _Rate = value; }
            get { return _Rate; }
        }
    }
}
